package com.itheima.mynetty.handler.client;

import com.itheima.netty.pojo.UserInfo;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class ClientInboundHandler1 extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("ClientInboundHandler1 channelActive-----");
        for (int i = 0; i < 100; i++) {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(i);
            userInfo.setName("name" + i);
            userInfo.setAge(i);
            userInfo.setGender(i % 2 == 0 ? "男" : "女");
            userInfo.setAddress("重庆");
//            ctx.writeAndFlush(ctx.alloc().buffer().writeBytes((userInfo.toString()).getBytes(StandardCharsets.UTF_8)));
//            MessageProto.Message message = MessageProto.Message.newBuilder().setId("1").setContent("hello protobuf").build();
//            ctx.writeAndFlush(message);
            ctx.writeAndFlush(userInfo);
        }

        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("ClientInboundHandler1 channelInactive-----");
        super.channelInactive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("ClientInboundHandler1 channelRead-----");

//        ByteBuf buf = (ByteBuf) msg;
//        byte[] bytes = new byte[buf.readableBytes()];
//        buf.readBytes(bytes);
//        String msg1 = new String(bytes, CharsetUtil.UTF_8);
//        System.out.println(msg1);
        super.channelRead(ctx, msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("ClientInboundHandler1 channelReadComplete-----");
        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("ClientInboundHandler1 exceptionCaught-----");
        super.exceptionCaught(ctx, cause);
    }
}
